<template>
  <div>
    <el-form class="addSupplygoodsOrder">
      <el-card
        v-if="state == 'edit1C' || state == 'editDC'"
        shadow="never"
        style="margin-top: 1%"
      >
        <template #header>
          <div style="display: flex; justify-content: space-between">
            <div class="card-header">
              <div
                style="
                  width: 4px;
                  height: 20px;
                  background-color: #409eff;
                  margin-right: 5px;
                "
              />
              <span>供货信息</span>
            </div>
            <div style="display: flex; justify-content: space-between">
              <!-- <el-button
                type="primary"
                color="#1E3485"
                @click="openViewForPurchaseyc()"
                >云采附件下载</el-button
              > -->
              <el-button
                type="primary"
                color="#1E3485"
                @click="rulesSubmit(ruleFormRef)"
                >提交供货</el-button
              >
              <div style="margin: 0 10px">
                <closeTagButton id="closeTagButtonRef" />
              </div>
            </div>
          </div>
        </template>
        <el-form
          ref="ruleFormRef"
          :model="formGH"
          label-width="150px"
          :rules="rulesForStepOne"
        >
          <el-row>
            <el-col :span="6">
              <el-form-item
                label="供货时间"
                style="width: 90%"
                prop="shipmentAt"
              >
                <el-date-picker
                  v-model="formGH.shipmentAt"
                  type="date"
                  placeholder=""
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="供货说明" style="width: 80%">
                <el-input
                  v-model="formGH.shipmentDesc"
                  placeholder=""
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="供货材料" style="width: 100%">
                <div style="width: 100%">
                  <vxe-table
                    border
                    min-height="300"
                    header-align="center"
                    :column-config="{ resizable: true }"
                    :row-config="{ isHover: true }"
                    :data="materialTableData"
                    size="mini"
                  >
                    <vxe-column
                      type="seq"
                      title="序号"
                      width="60"
                      align="center"
                    />
                    <vxe-column
                      field="materialCode"
                      title="材料编码"
                      width="120"
                    />
                    <vxe-column
                      field="materialName"
                      title="材料名称"
                      width="120"
                    />
                    <vxe-column
                      field="materialSpecs"
                      title="规格"
                      width="120"
                    />
                    <vxe-column
                      field="materialModel"
                      title="型号"
                      width="120"
                    />
                    <vxe-column field="materialUnit" title="单位" width="120" />
                    <vxe-column
                      field="materialBrand"
                      title="品牌"
                      width="120"
                    />
                    <vxe-column
                      field="orderCount"
                      title="订单数量"
                      fixed="right"
                      width="120"
                      show-overflow="ellipsis"
                    />
                    <vxe-column
                      field="supplyNum"
                      title="本次发货量"
                      fixed="right"
                      width="120"
                      show-overflow="ellipsis"
                    >
                      <template v-slot:default="{ row }">
                        <vxe-input
                          v-if="state == 'editDC'"
                          v-model="row.supplyNum"
                          type="number"
                          min="0"
                          @blur="updatesupplyNum(row)"
                        />
                        <span v-if="state == 'edit1C'">{{
                          row.supplyNum
                        }}</span>
                      </template>
                    </vxe-column>
                    <vxe-column
                      field="supplyCountNum"
                      title="已供货数量"
                      fixed="right"
                      width="120"
                      show-overflow="ellipsis"
                    />
                    <vxe-column
                      v-if="state == 'editDC'"
                      field=""
                      title="剩余发货量"
                      fixed="right"
                      width="120"
                      show-overflow="ellipsis"
                    >
                      <template v-slot:default="{ row }">
                        <span>{{
                          row.orderCount - row.supplyCountNum == undefined
                            ? 0
                            : row.orderCount - row.supplyCountNum
                        }}</span>
                      </template>
                    </vxe-column>
                    <vxe-column
                      field="contractIncludingTaxPrice"
                      title="含税单价(元)"
                      fixed="right"
                      width="120"
                      show-overflow="ellipsis"
                    />
                    <vxe-column
                      field="tax"
                      title="税率(%)"
                      fixed="right"
                      width="120"
                      show-overflow="ellipsis"
                    />
                    <vxe-column
                      field="includingTaxTotalPrice"
                      title="含税总金额(元)"
                      fixed="right"
                      width="120"
                      show-overflow="ellipsis"
                    />
                    <vxe-column
                      field="materialMark"
                      title="备注"
                      fixed="right"
                      width="120"
                      show-overflow="ellipsis"
                    />
                  </vxe-table>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>
          <div style="display: flex; justify-content: space-between">
            <div class="card-header">
              <div
                style="
                  width: 4px;
                  height: 20px;
                  background-color: #409eff;
                  margin-right: 5px;
                "
              />
              <span>基本信息</span>
            </div>
            <div>
              <!-- <el-button type="primary" color="#1E3485">保存并提交</el-button>
            <el-button type="primary" color="#1E3485">保存</el-button> -->
            </div>
          </div>
        </template>
        <el-form :model="form" label-width="150px" :rules="rulesForStepOne">
          <el-row>
            <el-col :span="24">
              <el-form-item label="采购合同" style="width: 90%">
                <el-select
                  v-model="form.contractName"
                  placeholder=""
                  disabled
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="订单编号" style="width: 80%">
                <el-input
                  v-model="form.orderSn"
                  placeholder=""
                  disabled
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单名称" style="width: 80%">
                <el-input
                  v-model="form.orderName"
                  placeholder=""
                  disabled
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="计划收货时间" style="width: 80%">
                <el-date-picker
                  v-model="form.receivingTime"
                  disabled
                  type="date"
                  placeholder=""
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="价格类型" style="width: 80%">
                <el-radio-group v-model="form.priceType" disabled class="ml-4">
                  <el-radio value="0">锁定</el-radio>
                  <el-radio value="1">浮动</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="支付说明" style="width: 90%">
                <el-input
                  v-model="form.priceTypeMark"
                  :rows="3"
                  type="textarea"
                  placeholder=""
                  disabled
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <div v-if="form.priceType == '1'">
            <el-row>
              <el-col :span="8">
                <el-form-item label="基准价" style="width: 90%">
                  <el-input
                    v-model="form.basePrice"
                    disabled
                    placeholder=""
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="涨幅" style="width: 90%">
                  <el-input
                    v-model="form.increasePrice"
                    disabled
                    placeholder=""
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="涨幅比率" style="width: 90%">
                  <el-input
                    v-model="form.increaseRate"
                    disabled
                    placeholder=""
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="当天铜价" style="width: 90%">
                  <el-input
                    v-model="form.copperPrice"
                    disabled
                    placeholder=""
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="铜价日期" style="width: 90%">
                  <el-date-picker
                    v-model="form.copperDate"
                    type="date"
                    placeholder=""
                    disabled
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="修改人" style="width: 90%">
                  <el-input
                    v-model="form.copperUpdatePersonName"
                    disabled
                    placeholder=""
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" style="width: 90%">
                <el-input
                  v-model="form.orderDesc"
                  disabled
                  placeholder=""
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="供货附件" style="width: 90%">
                <el-upload
                  v-model:file-list="form.attachFiles"
                  class="upload-demo"
                  :action="uploadUrl"
                  :on-preview="handlePreview"
                  multiple
                  :limit="3"
                >
                  <!-- <el-button type="primary" color="#1E3485"> 点击上传</el-button> -->
                  <template #tip>
                    <div
                      class="el-upload__tip"
                      style="width: 200px; margin-top: -40px !important"
                    />
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="云采附件" style="width: 90%">
                <el-upload
                  v-model:file-list="form.supplyConfirmFile"
                  class="upload-demo"
                  :action="uploadUrl"
                  :on-preview="handlePreview"
                  multiple
                  :limit="3"
                >
                  <!-- <el-button type="primary" color="#1E3485"> 点击上传</el-button> -->
                  <template #tip>
                    <div
                      class="el-upload__tip"
                      style="width: 200px; margin-top: -40px !important"
                    />
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card
        v-if="state != 'edit1C' && state != 'editDC'"
        shadow="never"
        style="margin-top: 1%"
      >
        <template #header>
          <div style="display: flex; justify-content: space-between">
            <div class="card-header">
              <div
                style="
                  width: 4px;
                  height: 20px;
                  background-color: #409eff;
                  margin-right: 5px;
                "
              />
              <span>申请材料</span>
              <div style="margin-left: 20px">
                <!-- <el-button type="primary" color="#1E3485" @click="showMaterial"
                >添加</el-button
              > -->
              </div>
              <div class="header-span">
                <div class="item">
                  <div
                    class="container"
                    style="
                      background: rgb(67, 94, 194);
                      color: rgb(255, 255, 255);
                    "
                  >
                    蓝色底色
                  </div>
                  <span>复制的材料</span>
                </div>
                <div class="item">
                  <div
                    class="container"
                    style="
                      background: rgb(245, 108, 108);
                      color: rgb(255, 255, 255);
                    "
                  >
                    红色底色
                  </div>
                  <span>订购数量大于合同量</span>
                </div>
                <div class="item">
                  <span
                    >提示：双击已订购数量，可查看当前材料的历史下单记录</span
                  >
                </div>
              </div>
            </div>
            <div>
              <el-button
                type="primary"
                color="#1E3485"
                @click="openViewForPurchase"
                >预览/下载</el-button
              >
            </div>
          </div>
        </template>
        <el-form label-width="150px">
          <vxe-table
            border
            min-height="300"
            header-align="center"
            :column-config="{ resizable: true }"
            :row-config="{ isHover: true }"
            :data="materialTableData"
            :row-style="rowStyle"
            size="mini"
          >
            <vxe-column type="seq" title="序号" width="60" align="center" />
            <vxe-column field="materialCode" title="材料编码" width="120" />
            <vxe-column field="materialName" title="材料名称" width="120" />
            <vxe-column field="materialSpecs" title="规格" width="120" />
            <vxe-column field="materialModel" title="型号" width="120" />
            <vxe-column field="materialUnit" title="单位" width="120" />
            <vxe-column field="materialBrand" title="品牌" width="120" />
            <vxe-column
              field="materialNum"
              title="合同数量"
              fixed="right"
              width="120"
              show-overflow="ellipsis"
            />
            <vxe-column
              field="checkNum"
              title="验收数量"
              fixed="right"
              width="120"
              show-overflow="ellipsis"
            />
            <vxe-column
              field="applyCountNum"
              title="已订购数量"
              fixed="right"
              width="120"
              show-overflow="ellipsis"
            />
            <vxe-column
              field="supplyCountNum"
              title="已供货数量"
              fixed="right"
              width="120"
              show-overflow="ellipsis"
            />
            <vxe-column
              field="orderCount"
              title="本次下单数量"
              fixed="right"
              width="120"
              show-overflow="ellipsis"
            />
            <vxe-column
              field="contractIncludingTaxPrice"
              title="合同含税单价(元)"
              fixed="right"
              width="120"
              show-overflow="ellipsis"
            />
            <vxe-column
              field="tax"
              title="税率(%)"
              fixed="right"
              width="120"
              show-overflow="ellipsis"
            />
            <vxe-column
              field="includingTaxTotalPrice"
              title="含税总金额(元)"
              fixed="right"
              width="120"
              show-overflow="ellipsis"
            />
            <vxe-column
              field="materialMark"
              title="备注"
              fixed="right"
              width="120"
              show-overflow="ellipsis"
            />
          </vxe-table>
        </el-form>
      </el-card>
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>
          <div style="display: flex; justify-content: space-between">
            <div class="card-header">
              <div
                style="
                  width: 4px;
                  height: 20px;
                  background-color: #409eff;
                  margin-right: 5px;
                "
              />
              <span>收货人</span>
              <div style="margin-left: 20px" />
            </div>
          </div>
        </template>
        <el-form label-width="150px">
          <vxe-table
            ref="tableRef"
            border
            :data="consigneeTableData"
            size="mini"
          >
            <vxe-column type="checkbox" fixed="left" width="40" />
            <vxe-column field="consigneeName" title="姓名" fixed="left" />
            <vxe-column field="consigneePhone" title="手机号" fixed="left" />
          </vxe-table>
        </el-form>
      </el-card>
      <!-- TODO 为什么注释了？ -->
      <!-- <el-card shadow="never" style="margin-top: 1%">
      <template #header>
        <div style="display: flex; justify-content: space-between">
          <div class="card-header">
            <div
              style="
                width: 4px;
                height: 20px;
                background-color: #409eff;
                margin-right: 5px;
              "
            ></div>
            <span>供应商确认</span>
          </div>
        </div>
      </template>
      <el-form label-width="150px">
        <vxe-table border ref="tableRef" :data="tableData">
          <vxe-column field="" title="状态" width="100" fixed="left" />
          <vxe-column field="" title="确认时间" width="400" fixed="left" />
          <vxe-column field="" title="确认说明" fixed="left" />
          <vxe-column field="" title="附件" fixed="left" />
        </vxe-table>
      </el-form>
    </el-card> -->
    </el-form>
    <!-- 弹窗组件 -->
    <div class="dialogs">
      <filePreview
        :visible="filePreviewVisible"
        :fileId="fileId"
        :fileType="fileType"
        @close="closeFilePreview"
      />
      <filePreview2
        :visible="filePreviewVisible2"
        :fileId="fileId"
        :fileType="fileType"
        :contractId="form.contractId"
        @close="closeFilePreview2"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import closeTagButton from "@/components/closeTagButton.vue";
import { Search, Upload } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { VxeTableInstance, VxePagerEvents } from "vxe-table";
import type {
  ComponentSize,
  FormInstance,
  FormRules,
  UploadProps,
  UploadFile
} from "element-plus";
import { useRouter, useRoute } from "vue-router";
import {
  getsupplyOrderOrderinfo,
  getmateriallistview,
  getmateriallist,
  getconsigneelist,
  saveposupply
} from "@/api/ERP_SupplyManage";
import { headers, uploadUrl, getDictDetail } from "@/api/utils";

import filePreview from "@/components/filePreview.vue";
import filePreview2 from "@/components/filePreview2.vue";
// 路由跳转
const route = useRoute();
// 页面状态
const state = ref(route.query.action);

onMounted(() => {
  getinfo();
});

const ruleFormRef = ref<FormInstance>();
//表单校验
const rulesForStepOne = reactive<FormRules>({
  shipmentAt: [{ required: true, message: "请选择供货时间", trigger: "blur" }]
});

// 表单数据
const form = ref({
  contractName: "",
  contractId: "",
  orderSn: "",
  orderName: "",
  id: "",
  receivingTime: "",
  priceType: "",
  priceTypeMark: "",
  basePrice: "",
  increasePrice: "",
  increaseRate: "",
  copperPrice: "",
  copperDate: "",
  copperUpdatePersonName: "",
  orderDesc: "",
  // 2处文件字段修改 和生产环境对齐 edit by YUM 240925
  attachFiles: [],
  projectConfirmFile: [],
  supplyConfirmFile: []
});

const formGH = reactive({
  shipmentAt: "",
  shipmentDesc: ""
});
// 表格数据
const materialTableData = ref([]);
const consigneeTableData = ref([]);

const handlePreview: UploadProps["onPreview"] = (uploadFile: UploadFile) => {
  if (uploadFile.response) {
    const response = uploadFile.response as unknown as any;
    window.open(response.data.url, "_blank");
  } else {
    window.open(uploadFile.url, "_blank");
  }
};
// 获取详情信息
const getinfo = async () => {
  const all = await getsupplyOrderOrderinfo({ id: route.query.id }).then(
    (response: any) => {
      form.value = response.data;
      // 文件处理 edit by YUM 240925
      if (response.data.attachFiles) {
        form.value.attachFiles = JSON.parse(response.data.attachFiles).map(
          file => ({
            name: file.fileOriginName,
            url: file.fileUrl
          })
        );
      } else {
        form.value.attachFiles = [];
      }
      if (response.data.projectConfirmFile) {
        const parsedFiles = JSON.parse(response.data.projectConfirmFile);
        form.value.projectConfirmFile = parsedFiles.map(file => ({
          name: file.fileOriginName,
          url: file.fileUrl
        }));
      } else {
        form.value.projectConfirmFile = [];
      }
      if (response.data.supplyConfirmFile) {
        form.value.supplyConfirmFile = JSON.parse(
          response.data.supplyConfirmFile
        ).map(file => ({
          name: file.fileOriginName,
          url: file.fileUrl
        }));
      } else {
        form.value.supplyConfirmFile = [];
      }

      getmaterial();
      getconsignee();
    }
  );
};
// 获取材料订单信息
const getmaterial = async () => {
  if (state.value == "view") {
    const all = await getmateriallistview({
      id: route.query.id,
      pageIndex: 1,
      pageSize: 999
    }).then((response: any) => {
      if (state.value == "view") {
        for (let i in response.data.records) {
          response.data.records[i].supplyNum =
            response.data.records[i].orderCount -
            response.data.records[i].supplyCountNum;
        }
      }
      materialTableData.value = response.data.records;
    });
  } else {
    const all = await getmateriallist({
      id: route.query.id,
      pageIndex: 1,
      pageSize: 999
    }).then((response: any) => {
      if (state.value == "edit1C" || state.value == "editDC") {
        for (let i in response.data) {
          response.data[i].supplyNum =
            response.data[i].orderCount - response.data[i].supplyCountNum;
        }
      }
      materialTableData.value = response.data;
    });
  }
};
// 获取收货人信息
const getconsignee = async () => {
  const all = await getconsigneelist({
    id: route.query.id,
    pageIndex: 1,
    pageSize: 999
  }).then((response: any) => {
    consigneeTableData.value = response.data.records;
  });
};

//验证
const rulesSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      pulsaveposupply();
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 提交供货
const pulsaveposupply = async () => {
  // for (let i in materialTableData.value) {
  //   if (
  //     materialTableData.value[i].supplyNum <
  //     materialTableData.value[i].orderCount -
  //       materialTableData.value[i].supplyCountNum
  //   ) {
  //     ElMessage.error("发货量超过最大数量，请检查发货量");
  //     return;
  //   }
  // }
  const all = await saveposupply({
    id: route.query.id,
    shipmentAt: formGH.shipmentAt,
    shipmentDesc: formGH.shipmentDesc,
    materialIdList: materialTableData.value
  }).then((response: any) => {
    if (response.code == 200) {
      document.getElementById("closeTagButtonRef").click();
      ElMessage.success("供货完成");
    } else {
      ElMessage.error(response.msg);
    }
  });
};
// 表格分页配置
const tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
});

// 表格分页事件
const handlePageChange: VxePagerEvents.PageChange = ({
  currentPage,
  pageSize
}) => {
  tablePage.currentPage = currentPage;
  tablePage.pageSize = pageSize;
};

//判断本次发货量不得超订单量
const updatesupplyNum = row => {
  if (row.supplyNum > row.orderCount - row.supplyCountNum) {
    ElMessage.error("本次发货量不能超出订单剩余数量请重新输入");
    row.supplyNum = 0;
  }
};

//单元格样式
const rowStyle = ({ row, rowIndex }) => {
  if (row.orderCount) {
    let applyCountNum = Number(
      row.applyCountNum == undefined ? 0 : row.applyCountNum
    );
    let orderCount = Number(row.orderCount == undefined ? 0 : row.orderCount);
    let materialNum = Number(
      row.materialNum == undefined ? 0 : row.materialNum
    );
    let sum = 0;
    for (let i in materialTableData.value) {
      if (materialTableData.value[i].materialCode === row.materialCode) {
        sum += Number(materialTableData.value[i].orderCount);
      }
    }
    if (applyCountNum + sum > materialNum) {
      if (row.isCopy === 0) {
        return {
          backgroundColor: "#f56c6c",
          color: "#ffffff"
        };
      }
    }
  }
  if (row.materialCode) {
    const tbas = materialTableData.value.map(item => item.materialCode);
    const tbaCount = tbas.filter(
      materialCode => materialCode === row.materialCode
    ).length;
    if (tbaCount > 1) {
      return { backgroundColor: "#435ec2", color: "#ffffff" };
    }
  }
};

// 预览弹窗
let filePreviewVisible = ref(false);
let filePreviewVisible2 = ref(false);
let fileId = ref("");
let fileType = ref("");
// 材料表格预览
function openViewForPurchase() {
  fileId.value = route.query.id as string;
  fileType.value = "supplyOrder";
  filePreviewVisible2.value = true;
}
// 云采表格预览
function openViewForPurchaseyc() {
  fileId.value = route.query.id as string;
  fileType.value = "supplyShippingOrder";
  filePreviewVisible.value = true;
}

function closeFilePreview(val: boolean) {
  filePreviewVisible.value = val;
}
function closeFilePreview2(val: boolean) {
  filePreviewVisible2.value = val;
}
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  align-items: center;
}
.header-span {
  display: flex;
  align-items: center;
}

.item {
  display: flex;
  align-items: center;
  margin-left: 20px;
  font-size: 12px;
}
.container {
  height: 20px;
  width: 80px;
  text-align: center;
  border: 1px solid #eee;
  line-height: 20px;
  font-size: 12px;
  margin-right: 6px;
  border-radius: 20px;
}
</style>
